package com.example.demo.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xiaohei.crm.common.exception.XiaoheiException;
import com.xiaohei.crm.common.result.Result;
import com.xiaohei.crm.common.result.ResultCodeEnum;
import com.xiaohei.crm.dao.Customer;
import com.xiaohei.crm.dao.Material;
import com.xiaohei.crm.dao.Orders;
import com.xiaohei.crm.dao.Region;
import com.xiaohei.crm.mapper.*;
import com.xiaohei.crm.service.OrdersService;
import lombok.RequiredArgsConstructor;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

import static com.xiaohei.crm.common.RedisEnums.ORDERS_UPDATE_LOCK;
import static com.xiaohei.crm.common.RedisEnums.ORDER_REGISTRY_KEY;
import static com.xiaohei.crm.common.result.ResultCodeEnum.DATA_ERROR;


@Service
@RequiredArgsConstructor
public class OrdersServiceImpl extends ServiceImpl<OrdersMapper, Orders> implements OrdersService {

    private final OrdersMapper ordersMapper;
    private final StringRedisTemplate stringRedisTemplate;
    private final RedissonClient redissonClient;

    private final CustomerMapper customerMapper;

    private final MaterialMapper materialMapper;

    private final InventoryMapper inventoryMapper;

    private final RegionMapper regionMapper;

    @Override
    public Result<IPage> findByPage(Integer pageIndex, Integer pageSize, String equipmentName, String customerName) {
        Page<Orders> page = new Page<>(pageIndex, pageSize);
        LambdaQueryWrapper<Orders> eq = Wrappers.lambdaQuery(Orders.class).eq(Orders::getDelFlag, 0);

        if(equipmentName != null){
            List<Integer> ids = new ArrayList<>();
            for (Material material : materialMapper.selectList(Wrappers.lambdaQuery(Material.class).like(Material::getEquipmentName, equipmentName))) {
                ids.add(material.getId());
            }
            if (ids.size() != 0){
                eq.in(Orders::getGoodsId, ids);
            }else {
                eq.in(Orders::getGoodsId, -1);
            }
        }

        if(customerName != null){
            List<Integer> ids = new ArrayList<>();
            for (Customer customer : customerMapper.selectList(Wrappers.lambdaQuery(Customer.class).like(Customer::getCustomerName, customerName))) {
                ids.add(customer.getId());
            }
            if (ids.size() != 0){
                eq.in(Orders::getCustomerId, ids);
            }else {
                eq.in(Orders::getCustomerId, -1);
            }
        }

        if(StrUtil.isNotBlank(customerName)){
            List<Integer> ids = new ArrayList<>();
            for (Customer customer : customerMapper.selectList(Wrappers.lambdaQuery(Customer.class).like(Customer::getCustomerName, customerName))) {
                ids.add(customer.getId());
            }
            if (ids.size() != 0){
                eq.in(Orders::getCustomerId, ids);
            }else {
                eq.in(Orders::getCustomerId, -1);
            }
        }

        Page<Orders> ordersPage = ordersMapper.selectPage(page, eq);
        for (Orders record : ordersPage.getRecords()) {
            Material material = materialMapper.selectById(record.getGoodsId());
            if (material != null) {
                record.setGoodsName(material.getEquipmentName());
            }
            Customer customer = customerMapper.selectById(record.getCustomerId());
            if (customer != null) {
                record.setCustomerName(customer.getCustomerName());
            }
            Region region = regionMapper.selectById(record.getArea());
            if (region != null) {
                record.setAreaName(region.getArea());
            }
        }
        return Result.ok(ordersPage);
    }

    @Override
    @Transactional
    public void saveOrders(Orders orders) {
        List<String> range = stringRedisTemplate
                .opsForList().range(ORDER_REGISTRY_KEY + orders.getId(), 0, -1);
        if (!CollectionUtil.isEmpty(range)) {
            throw new XiaoheiException(DATA_ERROR);
        }
        int i = inventoryMapper.reduceStockNum(orders.getGoodsId(), orders.getArea(), orders.getGoodsNumber());
        if (i < 1) {
            throw new XiaoheiException(ResultCodeEnum.STOCK_NOT_ENOUGH);
        }

        orders.setId(orders.getCustomerId().toString() + System.currentTimeMillis());
        int isInsert = ordersMapper.insert(orders);
        if (isInsert < 1) {
            throw new XiaoheiException(DATA_ERROR);
        }

        stringRedisTemplate.opsForList()
                .leftPushAll(ORDER_REGISTRY_KEY + orders.getId(), orders.getId(), orders.getId().toString());

    }

    @Override
    public void updateOrdersById(Orders orders) {
        RLock lock = redissonClient.getLock(ORDERS_UPDATE_LOCK + orders.getId());
        lock.lock();
        try {
            List<String> range = stringRedisTemplate.opsForList().range(ORDER_REGISTRY_KEY + orders.getId(), 0, -1);
            if (CollectionUtil.isEmpty(range)) {
                throw new XiaoheiException(DATA_ERROR);
            }

            LambdaQueryWrapper<Orders> eq =
                    Wrappers.lambdaQuery(Orders.class).eq(Orders::getId, orders.getId());
            int update = baseMapper.update(orders, eq);
            if(update < 1){
                throw new XiaoheiException(DATA_ERROR);
            }
            stringRedisTemplate.opsForList().set(ORDER_REGISTRY_KEY + orders.getId(),1,orders.getId().toString());
        }catch (Throwable e){
            e.printStackTrace();
        }finally {
            lock.unlock();
        }
    }

    @Override
    public void removeByOrdersId(String id) {
        List<String> range = stringRedisTemplate.opsForList().range(ORDER_REGISTRY_KEY + id, 0, -1);
        if (CollectionUtil.isEmpty(range)) {
            throw new XiaoheiException(DATA_ERROR);
        }

        LambdaUpdateWrapper<Orders> updateWrapper =
                Wrappers.lambdaUpdate(Orders.class).eq(Orders::getId, id);
        Orders orders = Orders.builder().delFlag(1).build();
        int update = baseMapper.update(orders, updateWrapper);
        if(update < 1){
            throw new XiaoheiException(DATA_ERROR);
        }
        stringRedisTemplate.delete(ORDER_REGISTRY_KEY + id);
    }

}
